package cc.rengu.redp.system.controller;

import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.redp.common.utils.EasyExcelUtil;
import cc.rengu.redp.system.domain.Dict;
import cc.rengu.redp.system.domain.DictRsVo;
import cc.rengu.redp.system.service.DictService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Slf4j
@Validated
@RestController
@RequestMapping("dict")
public class DictController extends BaseController {

    @Autowired
    private DictService dictService;

    @GetMapping
    @RequiresPermissions("dict:view")
    public Map<String, Object> DictList(QueryRequest request, Dict dict) {
        return getDataTable(this.dictService.findDicts(request, dict));
    }

    @Log("新增字典")
    @PostMapping
    @RequiresPermissions("dict:add")
    public RedpResponse addDict(String dictListJson) {
        List<Dict> dicts = new ArrayList<>();
        JSONObject jsonObject = JSON.parseObject(dictListJson);
        JSONArray jsonItems = jsonObject.getJSONArray("items");
        String fieldName = jsonObject.getString("fieldName");
        Iterator it = jsonItems.iterator();
        while (it.hasNext()) {
            JSONObject jsonItem = (JSONObject) it.next();
            Dict dict = new Dict();
            dict.setFieldName(fieldName);
            dict.setKeyy(jsonItem.getString("keyy"));
            dict.setValuee(jsonItem.getString("valuee"));
            dict.setGroupName("default");
            dicts.add(dict);
        }
        try {
            this.dictService.createDict(dicts);
        } catch (Exception e) {
            String message = "新增字典失败";
            log.error(message, e);
            return RedpResponse.getInstance().failure().message(message);
        }
        if (dicts.size()==0){
            return RedpResponse.getInstance().failure().message("新增字典失败，键值不能为空");
        }
        return RedpResponse.getInstance().success().message("新增字典成功");
    }

    @Log("删除字典")
    @DeleteMapping("/{dictIds}")
    @RequiresPermissions("dict:delete")
    public RedpResponse deleteDicts(@NotBlank(message = "{required}") @PathVariable String dictIds) {
        try {
            String[] ids = dictIds.split(StringPool.COMMA);
            this.dictService.deleteDicts(ids);
        } catch (Exception e) {
            String message = "删除字典失败";
            log.error(message, e);
            return RedpResponse.getInstance().failure().message(message);
        }

        return RedpResponse.getInstance().success().message("删除字典成功");
    }

    @Log("修改字典")
    @PutMapping
    @RequiresPermissions("dict:update")
    public RedpResponse updateDict(@Valid Dict dict) {
        try {
            this.dictService.updateDict(dict);
        } catch (Exception e) {
            String message = "修改字典失败";
            log.error(message, e);
            return RedpResponse.getInstance().failure().message(message);
        }

        return RedpResponse.getInstance().success().message("修改字典成功");
    }

    @Log("查询指定字段的字典列表")
    @GetMapping("getField")
    public List<DictRsVo> getDictField(String group, String field) {
        List<Dict> dicts = this.dictService.getDictByField("default", field);
        List<DictRsVo> dictRsVos = new ArrayList<>();
        dicts.forEach(dict -> dictRsVos.add(new DictRsVo(dict.getKeyy(), dict.getValuee())));
        return dictRsVos;
    }

    @Log("导出字典")
    @PostMapping("excel")
    @RequiresPermissions("dict:export")
    public RedpResponse export(QueryRequest request, Dict dict, HttpServletResponse response) {
        try {
            List<Dict> dicts = this.dictService.findDicts(request, dict).getRecords();
            EasyExcelUtil.export(response, dicts, "字典数据");
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            return RedpResponse.getInstance().failure().message(message);
        }

        return RedpResponse.getInstance().success().message("导出Excel成功");
    }
}
